package org.example.backend.Base.Config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.IOException;

@Slf4j
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        StringRedisSerializer keySerializer = new StringRedisSerializer();
        MyRedisSerializer<Object> valueSerializer = new MyRedisSerializer<>();

        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);

        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);

        redisTemplate.setConnectionFactory(factory);

        return redisTemplate;
    }

    static class MyRedisSerializer<T> implements RedisSerializer<T> {
        ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public byte[] serialize(T t) throws SerializationException {
            if(t == null) return new byte[0];

            try {
                return objectMapper.writeValueAsBytes(t);
            } catch (JsonProcessingException e) {
                log.error("Redis serialize error: {}", e.getOriginalMessage());

                return new byte[0];
            }
        }

        @Override
        public T deserialize(byte[] bytes) throws SerializationException {
            if(bytes == null || bytes.length == 0) return null;

            try {
                return objectMapper.readValue(bytes, new TypeReference<T>() {});
            } catch (IOException e) {
                log.error("Redis deserialize error: {}", e.getMessage());

                return null;
            }
        }
    }
}
